// pages/userPhoto/userPhoto.js
//获取应用实例
const app = getApp()
import {
  Router
} from '../../utils/router.js'
import constant from './constant.js'
import config from '../../config/index';
import RewardedAds from '../../utils/rewarded-ads';

const instanceRewardedAds  = new RewardedAds(config.rewardAdsSaveHead);
Router({
  /**
   * 页面的初始数据
   */
  data: {
    isiPhoneX: false,
    userImage: 'https://qiniu.bigerfe.com/default_avator.jpeg',
    new_userImage: '',
    new_showuserImage: false,
    userInfo: {},
    hasUserInfo: true,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    photo_bj_num: constant.Head_TIP_PIC,
    photo_select_idx: 0,
    indexAdCode: config.indexAdCode,
    indexPageAdCode: config.indexPageAdCode
  },

  // 插屏广告
  initAdShow() {
    // 在页面中定义插屏广告
    let interstitialAd = null

    // 在页面onLoad回调事件中创建插屏广告实例
    if (wx.createInterstitialAd) {
      interstitialAd = wx.createInterstitialAd({
        adUnitId: this.data.indexPageAdCode
      })
      interstitialAd.onLoad(() => {})
      interstitialAd.onError((err) => {})
      interstitialAd.onClose(() => {})
    }

    // 在适合的场景显示插屏广告
    if (interstitialAd) {
      interstitialAd.show().catch((err) => {
        console.error(err)
      })
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function () {
    const initAvator = getApp().globalData?.initAvator;
    if (initAvator) {
      this.setData({
        userImage: getApp().globalData?.initAvator,
      });
    }
    this.initAdShow();
    //初始化激励性广告
    instanceRewardedAds.adInit();
  },
  onChooseAvatar(e) {
    const {
      avatarUrl
    } = e.detail;
    console.log(avatarUrl)
    this.setUserCusPhoto(avatarUrl);
  },
  /**
   * 用户点击获取图片
   */
  tapWxAvator: function () {
    this.getUSerWechatInfo_Photo();
  },

  tapOpenPhoto() {
    this.getUSerMobile_Photo();
  },

  /**
   * 下载用户微信头像
   */
  setUserWeCahtPhoto: function (url) {
    let that = this
    console.log('url', url);
    getApp().globalData.initAvator = url;
    wx.downloadFile({
      url: that.headimgHD(url),
      success: function (res) {
        if (res.statusCode === 200) {
          that.drawImg(res.tempFilePath, that.data.photo_select_idx);
        }
      }
    })
  },

  /**
   * 下载截图页面返回的图片
   */
  setUserCusPhoto: function (url) {
    getApp().globalData.initAvator = url;
    this.drawImg(url, this.data.photo_select_idx);
  },

  //从自定义图片页面返回调用的方法，需要增加延迟，否则会出现神器的问题
  setFromCusPhotoBack: function (url) {
    wx.showLoading({
      title: '处理中...',
    })
    setTimeout(() => {
      this.setUserCusPhoto(url);
    }, 1500);
  },

  /**
   * 获取用户微信头像
   */
  getUSerWechatInfo_Photo: function () {
    let that = this
    wx.getUserProfile({
      desc: '不需要再次上传',
      success: res => {
        app.globalData.userInfo = res.userInfo
        that.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
        that.setUserWeCahtPhoto(app.globalData.userInfo.avatarUrl);
      },
      fail: error => {
        console.log('fail', error);
      },
      complete: data => {
        console.log('complete', data);
      }
    })
    //}
  },

  /**
   * 打开用户相册
   */
  getUSerMobile_Photo: function () {
    let that = this
    // let index = e.currentTarget.dataset.index
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album'],
      success(res) {
        // tempFilePath可以作为img标签的src属性显示图片
        let tempFilePath = res.tempFilePaths[0];
        wx.navigateTo({
          url: `/pages/avatarUpload/upload/upload?src=${tempFilePath}`
        });
      },
      fail: function (res) {
        console.log(res.errMsg)
      }
    });
  },
  /**
   * 重置画布
   */
  editClick: function () {
    this.setData({
      hasUserInfo: false,
      userImage: '',
      new_userImage: '',
      new_showuserImage: false
    })
  },

  /**
   * 获取高清微信头像
   */
  headimgHD: function (imageUrl) {
    imageUrl = imageUrl.split('/');
    if (imageUrl[imageUrl.length - 1] &&
      (imageUrl[imageUrl.length - 1] == 46 || imageUrl[imageUrl.length - 1] == 64 || imageUrl[imageUrl.length - 1] == 96 || imageUrl[imageUrl.length - 1] == 132)) {
      imageUrl[imageUrl.length - 1] = 0;
    }
    imageUrl = imageUrl.join('/');
    return imageUrl;
  },
  saveloadFile: function () {
    if (!this.data.new_userImage) {
      wx.showModal({
        content: '没有图片可保存~',
        showCancel: false,
        confirmText: '明白了',
      })
      return
    }
    //展示激励性广告
    if(!instanceRewardedAds.isEnded){
      instanceRewardedAds.showAd();
      return;
    }
    wx.showLoading({
      title: '保存中...'
    })
    let that = this
    wx.saveImageToPhotosAlbum({
      filePath: that.data.new_userImage,
      success(res) {
        wx.hideLoading();
        wx.showModal({
          content: '图片已保存到相册了~',
          showCancel: false,
          confirmText: '保存成功',
          success(res) { 
            if (res.confirm) {
              console.log("点击确定,老铁没毛病");
              instanceRewardedAds.resetAd(); //下次还需要继续看广告
            }
          }
        })
      },
      fail(){
        wx.hideLoading();
        instanceRewardedAds.resetAd(); //下次还需要继续看广告
      }
    })
  },
  bigimg: function (e) {
    if (this.data.userImage) {
      this.setData({
        photo_select_idx: e.currentTarget.dataset.item
      });
      this.drawImg(this.data.userImage, this.data.photo_select_idx);
    }
  },
  //绘图
  drawImg(headImg, index) {
    let that = this
    wx.showLoading({
      title: '头像生成中...',
    })

    let promiseHead = new Promise((resolve, reject) => {
      wx.getImageInfo({
        src: headImg,
        success(res) {
          resolve(res)
        },
        fail(e) {
          reject("调用失败head");
          wx.hideLoading()
        }
      })
    })
    Promise.all([promiseHead]).then(promiseRes => {
      let num = 1024
      let width_userIcon = num
      let x_userIcon = (num - (num)) / 2
      let frameImgUrl = that.data.photo_bj_num[index];
      const query = wx.createSelectorQuery()
      query.select('#genimg')
        .fields({
          node: true,
          size: true
        })
        .exec((res) => {
          const canvas = res[0].node
          const ctx = canvas.getContext('2d');
          // 初始化画布大小
          const dpr = wx.getWindowInfo().pixelRatio;
          canvas.width = 1024 * dpr
          canvas.height = 1024 * dpr
          ctx.scale(dpr, dpr)
          const bg1 = canvas.createImage();
          const bg2 = canvas.createImage();
          bg1.src = promiseRes[0].path;
          bg1.onload = () => {
            ctx.drawImage(bg1, x_userIcon, x_userIcon, width_userIcon, width_userIcon);
            bg2.onload = () => {
              ctx.drawImage(bg2, 0, 0, num, num);
            }
            bg2.src = frameImgUrl;
          }
          setTimeout(() => {
            // 第一个参数为false，表示先清空画布再绘制
            wx.canvasToTempFilePath({
              x: 0,
              y: 0,
              width: num,
              height: num,
              destWidth: num,
              destHeight: num,
              canvas,
              quality: 1,
              success(res) {
                that.setData({
                  new_userImage: res.tempFilePath,
                  new_showuserImage: true,
                  userImage: headImg
                })
                wx.hideLoading()
              },
              fail(res) {
                console.log("绘图错误：" + JSON.stringify(res));
                wx.hideLoading();
              }
            }, that);
          }, 1000);
        })
    }).catch(e => console.log(e));
  }
})